package com.huhao.wshare.Profile;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.huhao.wshare.LoginActivity;
import com.huhao.wshare.R;
import com.huhao.wshare.Refreshable;

import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

import static com.huhao.wshare.Config.GET_USER_PROFILE_API;

public class ProfileFragment extends Fragment implements Refreshable {
    private TextView tvUsername, tvAccount, tvEmail, tvPhone, tvSigns;
    private ImageView ivAvatar, ivBackground, ivGender;
    private String userId, token;
    private ImageButton btnSettings;
    private OkHttpClient client = new OkHttpClient();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile, container, false);

        // 初始化视图
        tvUsername = view.findViewById(R.id.tvUsername);
        tvAccount = view.findViewById(R.id.tvAccount);
        tvEmail = view.findViewById(R.id.tvEmail);
        tvPhone = view.findViewById(R.id.tvPhone);
        tvSigns = view.findViewById(R.id.tvSigns);
        ivAvatar = view.findViewById(R.id.ivAvatar);
        ivBackground = view.findViewById(R.id.background_image);
        ivGender = view.findViewById(R.id.ivGender);
        btnSettings = view.findViewById(R.id.btnSettings);
        LinearLayout llMomentsEntry = view.findViewById(R.id.ll_moments_entry);

        // 从 SharedPreferences 中获取用户信息
        SharedPreferences sp = requireActivity().getSharedPreferences("user_prefs", requireContext().MODE_PRIVATE);
        userId = String.valueOf(sp.getInt("id", -1));
        token = sp.getString("token", null);
        if (userId != null && !userId.equals("-1") && token != null) {
            // 获取用户信息
            fetchUserProfile();
        } else {
            // 用户未登录，跳转到登录页
            startActivity(new Intent(requireActivity(), LoginActivity.class));
            requireActivity().finish();
        }
        // 点击设置按钮
        btnSettings.setOnClickListener(v -> {
            Intent intent = new Intent(requireActivity(), SettingActivity.class);
            startActivity(intent);
        });
        // 点击进入我的动态空间
        llMomentsEntry.setOnClickListener(v -> {
            Intent intent = new Intent(requireActivity(), MyDynamicActivity.class);
            startActivity(intent);
        });
        return view;
    }

    @Override
    public void refresh() {
        fetchUserProfile();
    }


    @Override
    public void onResume() {
        super.onResume();
        if (userId != null && !userId.equals("-1") && token != null) {
            refresh();
        }
    }

    private void fetchUserProfile() {
        // 构建请求头，包含 Authorization
        Request request = new Request.Builder()
                .url(GET_USER_PROFILE_API + "/" + userId)
                .get()
                .addHeader("Authorization", "Bearer " + token)
                .build();

        // 发送网络请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "网络错误，请稍后重试", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String respStr = response.body() != null ? response.body().string() : "";
                    requireActivity().runOnUiThread(() -> handleProfileResponse(respStr));
                } else {
                    requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "获取用户信息失败，请稍后重试", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

    private void handleProfileResponse(String respStr) {
        try {
            JSONObject json = new JSONObject(respStr);
            int code = json.optInt("code");
            if (code == 200) {
                JSONObject data = json.optJSONObject("data");
                if (data != null) {
                    // 更新 UI 组件的文本
                    tvUsername.setText(data.optString("username"));
                    tvAccount.setText("wshare账号：" + data.optString("account"));
                    tvEmail.setText(data.optString("email"));
                    tvPhone.setText(data.optString("phone"));
                    tvSigns.setText((data.optString("signs") != null ? data.optString("signs") : "暂无个性签名"));

                    String avatarUrl = data.optString("avatar");
                    if (!data.isNull("avatar") && !avatarUrl.isEmpty()) {
                        Glide.with(this)
                                .load(avatarUrl)
                                .into(ivAvatar);
                    } else {
                        String gender = data.optString("gender");
                        if ("man".equals(gender)) {
                            ivAvatar.setImageResource(R.drawable.default_avatar_man);
                        } else if ("woman".equals(gender)) {
                            ivAvatar.setImageResource(R.drawable.default_avatar_woman);
                        } else {
                            ivAvatar.setImageResource(R.drawable.default_avatar_man);
                        }
                    }

                    String bkImgUrl = data.optString("bkImg");
                    if (!data.isNull("bkImg") && !bkImgUrl.isEmpty()) {
                        Glide.with(this)
                                .load(bkImgUrl)
                                .into(ivBackground);
                    } else {
                        ivBackground.setImageResource(R.drawable.default_background);
                    }

                    String gender = data.optString("gender");
                    if ("man".equals(gender)) {
                        ivGender.setImageResource(R.drawable.ic_male);
                        ivGender.setVisibility(View.VISIBLE);
                    } else if ("woman".equals(gender)) {
                        ivGender.setImageResource(R.drawable.ic_female);
                        ivGender.setVisibility(View.VISIBLE);
                    } else {
                        ivGender.setVisibility(View.GONE);
                    }

                    Log.i("Avatar & BkImg", avatarUrl + " " + bkImgUrl);
                    SharedPreferences sp = requireActivity().getSharedPreferences("user_prefs", requireContext().MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("username", data.optString("username"));
                    editor.putString("account", data.optString("account"));
                    editor.putString("email", data.optString("email"));
                    editor.putString("phone", data.optString("phone"));
                    editor.putString("signs", data.optString("signs"));
                    editor.putString("avatar", avatarUrl);
                    editor.putString("bkImg", bkImgUrl);
                    editor.putString("gender", gender);
                    editor.apply();
                }
            } else {
                Toast.makeText(requireContext(), json.optString("message"), Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(requireContext(), "解析用户信息失败", Toast.LENGTH_SHORT).show();
            Log.e("Profile", "解析 JSON 失败", e);
        }
    }
}